import json
import datetime
import configparser
import os
from base_server.diyMySql import *

class TaskImpl(object):
    def __init__(self):
        self.DB = self.getConn()



    def getConn(self):
        config = configparser.ConfigParser()
        path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
        my_path = path + "/" + "conf/config.ini"
        config.read(my_path)
        host = config["ci"]["host"]
        username = config["ci"]["user"]
        password = config["ci"]["passwd"]
        database = config["ci"]["database"]
        print(host)
        dataBaseHandle = DataBaseHandle(host, username, password, database, port=3306)
        return dataBaseHandle
    def selectOne(self, id):
        sql = "SELECT * FROM job_task WHERE id = %s"
        args = (id,)
        result = self.DB.selectDb(sql,args)
        dict = {
            "id": result[1][0][0],
            "task_name": result[1][0][1],
            "job_name": result[1][0][2],
            "status": result[1][0][3],
            "ding_token": result[1][0][4],
            "create_time": str(result[1][0][5]),
        }
        return json.dumps(dict, ensure_ascii=False)

    def deleteTask(self, id):
        args = (id)
        sql = "UPDATE job_task SET status = 0 WHERE id = %s;"
        self.DB.updateDb(sql, args)


    def selectAll(self):
        sql = "SELECT * FROM job_task;"
        listhead = ("id", "task_name", "job_name", "status", "ding_token", "create_time")
        l = []
        d={}
        for i in self.DB.selectDb(sql)[1]:
            if i[3] == 0:
                continue
            else:
                result1 = dict.fromkeys(listhead, )
                result1["id"] = i[0]
                result1["task_name"] = i[1]
                result1["job_name"] = i[2]
                result1["status"] = i[3]
                result1["ding_token"] = i[4]
                result1["create_time"] = str(i[5])
                l.append(result1)
        import json
        d = {"code":0, "msg":"","count":len(l), "data": l}

        return json.dumps(d, ensure_ascii=False)


    def insertOne(self,task_name,job_name,ding_token):
        create_time = time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        create_time = str(create_time)
        status = 1
        sql = "INSERT INTO job_task (task_name, job_name,status, ding_token,create_time) VALUES (%s, %s, %s, %s, %s)"
        args = (task_name,job_name,status,ding_token,create_time)
        self.DB.insertDB(sql, args)

    def delteOne(self,id):
        args = (id,)
        sql = """DELETE FROM job_task WHERE id = %s;"""
        self.DB.deleteDB(sql, args)

    def update(self,id,task_name,job_name,status,ding_token):
        args = (task_name,job_name,status,ding_token,id)
        sql = "UPDATE job_task SET task_name= %s, job_name =  %s, status = %s, ding_token = %s WHERE id = %s;"
        self.DB.updateDb(sql, args)


    def selectTaskCiYapi(self,task_id):
        sql = "SELECT * FROM ci_yapi WHERE task_id = %s;"
        args = (task_id,)
        return self.DB.selectDb(sql, args)

    def parse_list(self):
        listhead = ("id", "task_name", "job_name", "status", "ding_token", "create_time")

    def query_task_ci(self, task_id):
        sql = """
        SELECT jt.id, jt.task_name, jt.job_name,jt.status, jt.ding_token, jt.create_time,cy.id, cy.case_col,cy.yapi_url
        FROM job_task as jt LEFT JOIN ci_yapi as cy ON jt.id = cy.task_id
        WHERE task_id = %s;
        """
        args = (task_id,)
        res= self.DB.selectDb(sql, args)
        res_head = (
        "jt_id", "jt_task_name", "jt_job_name","jt_status", "jt_ding_token", "jt_create_time", "cy_id", "cy_case_col", "cy_yapi_url")
        dict = {}
        datalist = []
        for i in res[1]:
            dick_key = dict.fromkeys(res_head, )
            dick_key["jt_id"] = i[0]
            dick_key["jt_task_name"] = i[1]
            dick_key["jt_job_name"] = i[2]
            dick_key["jt_status"] = i[3]
            dick_key["jt_ding_token"] = i[4]
            dick_key["jt_create_time"] = str(i[5])
            dick_key["cy_id"] = i[6]
            dick_key["cy_case_col"] = i[7]
            dick_key["cy_yapi_url"] = i[8]
            datalist.append(dick_key)
        import json
        dict = {"code": res[0], "msg": "查询task和ci", "data": datalist}
        json.dumps(dict, ensure_ascii=False)
        return dict



if __name__ == '__main__':
    t= TaskImpl()
    t.selectAll()